import loginService from '@/service/loginService.js'
import cacheHandler from '@/utils/cacheHandler.js'
import { config } from '@/config/systemConfig.js'
import showModal from '@/utils/showModalHandler.js'
import common from '@/utils/common.js'
import { provider, terminal } from '@/config/const.js'

function setTerminalId() {
  const res = uni.getSystemInfoSync()
  // 缓存系统参数
  cacheHandler.setSystemInfo(res)

  // #ifdef MP-WEIXIN
  cacheHandler.setTerminalId(terminal.WX_MINI_CLIENT)
  // #endif

  // #ifdef MP-ALIPAY
  cacheHandler.setTerminalId(terminal.ZFB_MINI_CLIENT)
  console.log('terminalId cache', cacheHandler.getTerminalId())
  // #endif

  if (res.ua) {
    // 微信服务号
    if (common.isWeChatBrowser(res.ua)) {
      cacheHandler.setTerminalId(terminal.WX_CLIENT)
      // 支付宝生活号
    } else if (common.isAlipayBrowser(res.ua)) {
      cacheHandler.setTerminalId(terminal.ZFB_CLIENT)
      // 微站
    } else {
      cacheHandler.setTerminalId(terminal.MS_CLIENT)
    }
  }
}

function cacheInfo(res) {
  cacheHandler.setOpenId(res.openId)
  cacheHandler.setUnionId(res.unionId ? res.unionId : res.openId)
  cacheHandler.setDhccAppId(res.dhccamAppId)
  console.log('dhccAppId', cacheHandler.getDhccAppId())
  const crypto = {
    cryptoIV: res.cryptoIV,
    cryptoKey: res.cryptoKey,
    cryptoSignKey: res.cryptoSignKey,
    cryptoSignType: res.cryptoSignType,
    cryptoType: res.cryptoType
  }
  cacheHandler.setCrypto(crypto)
  console.log('crypto', cacheHandler.getCrypto())
}

function login() {
  return new Promise(function(resolve, reject) {
    common.getProvider(provider.OAUTH).then(res => {
      console.log('getProvider', res)
      // h5环境时为[]
      if (res.provider.length > 0) {
        miniLogin(res.provider[0]).then(res => {
          console.log('login', res)
          cacheInfo(res)
          resolve(res)
        }).catch((err) => {
          console.log(err)
          showModal.showConfirmModal(err)
          reject(err)
        })
      } else {
        h5Login().then(res => {
          console.log('h5Login', res)
          cacheInfo(res)
          resolve(res)
        }).catch((err) => {
          console.log(err)
          showModal.showConfirmModal(err)
          reject(err)
        })
      }
    }).catch(err => {
      showModal.showConfirmModal(err)
    })
  })
}

// 支付宝和微信小程序组装参数条件判断
function miniLogin(provider) {
  return new Promise(function(resolve, reject) {
    uni.login({
      provider: provider,
      success: function(loginRes) {
        console.log('loginRes', loginRes)
        const request = {
          appId: config.APPID_MINI_CLIENT,
          code: loginRes.code,
          terminalId: cacheHandler.getTerminalId(),
          deviceId: cacheHandler.getSystemInfo().deviceId,
          deviceModel: cacheHandler.getSystemInfo().deviceModel
        }
        miniMixedLogin(request).then(result => {
          resolve(result)
        }).catch(err => {
          reject(err)
        })
      },
      fail: function(err) {
        reject(err.errMsg)
      }
    })
  })
}

/**
 * 微信支付宝小程序授权登录
 */
function miniMixedLogin(request) {
  console.log('login request', request)
  return new Promise(function(resolve, reject) {
    loginService.miniMixedLogin(request).then(result => {
      if (result.code !== 20000) {
        reject(result.msg)
      }
      if (!result.openId) {
        reject('no openId')
      }
      resolve(result)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 服务号、生活号和微站授权
 */
function h5Login() {
  return new Promise(function(resolve, reject) {
    let terminalId = cacheHandler.getTerminalId()
    console.log('terminalId', terminalId)
    if (terminalId === terminal.MS_CLIENT) {
      msClientLogin().then(result => {
        resolve(result)
      }).catch(err => {
        reject(err)
      })
    } else {
      h5Mixed().then(result => {
        resolve(result)
      }).catch(err => {
        reject(err)
      })
    }
  })
}

/**
 * 公众号服务号组装参数，条件判断
 */
function h5Mixed() {
  return new Promise(function(resolve, reject) {
    let terminalId = cacheHandler.getTerminalId()
    let code = '' // 生活号服务号登录所需的code
    let url = '' // 生活号服务号登录授权请求的url
    let appId = '' // 生活号或者服务号的appId
    let authUrl = '' // 生活号服务号官方获取code请求的url
    if (terminalId === terminal.WX_CLIENT) {
      code = getUrlCode().code
      url = config.LOGIN_URL_WX_CLIENT
      appId = config.APPID_WX_CLIENT
      authUrl = config.AUTH_URL_WX_CLIENT
    }

    if (terminalId === terminal.ZFB_CLIENT) {
      code = getUrlCode().auth_code
      url = config.LOGIN_URL_ZFB_CLIENT
      appId = config.APPID_ZFB_CLIENT
      authUrl = config.AUTH_URL_ZFB_CLIENT
    }

    console.log('auth code', code)
    if (code) {
      const request = {
        appId: appId,
        code: code,
        terminalId: terminalId,
        deviceId: cacheHandler.getSystemInfo().deviceId,
        deviceModel: cacheHandler.getSystemInfo().deviceModel,
        url: url
      }
      console.log('h5MixedLogin request', request)
      h5MixedLogin(request).then(result => {
        resolve(result)
      }).catch(err => {
        reject(err)
      })
    } else {
      let uri = config.AUTH_RETURN_URI // 获取code后回调地址
      uri = encodeURIComponent(uri)
      authUrl = common.regexReplace(authUrl, appId, uri)
      console.log('auth url：', authUrl)
      window.location.href = authUrl
    }
  })
}

/**
 * 公众号服务号授权登录
 */
function h5MixedLogin(request) {
  console.log('login request', request)
  return new Promise(function(resolve, reject) {
    loginService.h5MixedLogin(request).then(result => {
      if (result.code !== 20000) {
        reject(result.msg)
      }
      if (!result.openId) {
        reject('no openId')
      }
      resolve(result)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 微站授权登录
 */
function msClientLogin() {
  return new Promise(function(resolve, reject) {
    // if (!cacheHandler.getMsClientUserInfo().phoneNo || !cacheHandler.getMsClientUserInfo().passwd) {
    //   uni.reLaunch({
    //   	url: '/pages/h5-login/index'
    //   })
    //   return
    // }
    const request = {
      // phoneNo: cacheHandler.getMsClientUserInfo().phoneNo,
      // passwd: cacheHandler.getMsClientUserInfo().passwd,
      phoneNo: '18660824890',
      passwd: '123456',
      appId: '12345678',
      terminalId: cacheHandler.getTerminalId(),
      deviceId: cacheHandler.getSystemInfo().deviceId,
      deviceModel: cacheHandler.getSystemInfo().deviceModel
    }
    console.log('msClientLogin request', request)
    loginService.msClientLogin(request).then(result => {
      if (result.code !== 20000) {
        reject(result.msg)
      }
      if (!result.openId) {
        reject('no openId')
      }
      cacheHandler.clearMsClientUserInfo()
      resolve(result)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 截取服务号和生活号获取code重定向回来的参数
 */
function getUrlCode() {
  var url = location.search
  var theRequest = new Object()
  if (url.indexOf('?') !== -1) {
    var str = url.substr(1)
    var strs = str.split('&')
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
    }
  }
  return theRequest
}

export default {
  login,
  setTerminalId
}
